/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
var spiralOrder = function (matrix) {
  let m = matrix.length, n = matrix[0].length
  let total = m * n, directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]
  let directionIndex = 0, res = [], row = 0, column = 0
  let visited = new Array(m).fill(0).map(() => new Array(n).fill(false))
  for (let i = 0; i < total; i++) {
    res[i] = matrix[row][column]
    visited[row][column] = true
    let nextRow = row + directions[directionIndex][0], nextColumn = col + directions[directionIndex][1]
    if (!(nextRow >= 0 && nextRow < m && nextColumn >= 0 && nextColumn < n && !visited[nextRow][nextColumn])) {
      directionIndex = (directionIndex + 1) % 4
    }
    row += directions[directionIndex][0]
    column += directions[directionIndex][1]
  }
};

spiralOrder([[1, 2, 3], [4, 5, 6], [7, 8, 9]])